<%#
 Copyright 2013-2020 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
package <%= packageName %>.security;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
<%_ if (authenticationType === 'oauth2') { _%>
import org.springframework.security.core.authority.SimpleGrantedAuthority;
<%_ } _%>
<%_ if (reactive) { _%>
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
<%_ } _%>
import org.springframework.security.core.context.SecurityContext;
<%_ if (!reactive) { _%>
import org.springframework.security.core.context.SecurityContextHolder;
<%_ } _%>
import org.springframework.security.core.userdetails.UserDetails;
<%_ if (authenticationType === 'oauth2') { _%>
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
<%_ } _%>
<%_ if (reactive) { _%>
import reactor.core.publisher.Mono;
<%_ } _%>

<%_ if (authenticationType === 'oauth2') { _%>
import java.util.*;
import java.util.stream.Collectors;
<%_ } _%>
<%_ if (!reactive) { _%>
    <%_ if (authenticationType !== 'oauth2') { _%>
import java.util.Optional;
    <%_ } _%>
import java.util.stream.Stream;
<%_ } _%>

/**
 * Utility class for Spring Security.
 */
public final class SecurityUtils {

    private SecurityUtils() {
    }

    /**
     * Get the login of the current user.
     *
     * @return the login of the current user.
     */
    public static <% if (!reactive) { %>Optional<% } else { %>Mono<% } %><String> getCurrentUserLogin() {
<%_ if (!reactive) { _%>
        SecurityContext securityContext = SecurityContextHolder.getContext();
        return Optional.ofNullable(extractPrincipal(securityContext.getAuthentication()));
<%_ } else { _%>
        return ReactiveSecurityContextHolder.getContext()
            .map(SecurityContext::getAuthentication)
            .flatMap(authentication -> Mono.justOrEmpty(extractPrincipal(authentication)));
<%_ } _%>
    }

    private static String extractPrincipal(Authentication authentication) {
        if (authentication == null) {
            return null;
        } else if (authentication.getPrincipal() instanceof UserDetails) {
            UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
            return springSecurityUser.getUsername();
<%_ if (authenticationType === 'oauth2') { _%>
        } else if (authentication instanceof JwtAuthenticationToken) {
            return (String) ((JwtAuthenticationToken)authentication).getToken().getClaims().get("preferred_username");
        } else if (authentication.getPrincipal() instanceof DefaultOidcUser) {
            Map<String, Object> attributes = ((DefaultOidcUser) authentication.getPrincipal()).getAttributes();
            if (attributes.containsKey("preferred_username")) {
                return (String) attributes.get("preferred_username");
            }
<%_ } _%>
        } else if (authentication.getPrincipal() instanceof String) {
            return (String) authentication.getPrincipal();
        }
        return null;
    }

<%_ if (authenticationType === 'jwt') { _%>

    /**
     * Get the JWT of the current user.
     *
     * @return the JWT of the current user.
     */
    public static <% if (!reactive) { %>Optional<% } else { %>Mono<% } %><String> getCurrentUserJWT() {
        <%_ if (!reactive) { _%>
        SecurityContext securityContext = SecurityContextHolder.getContext();
        return Optional.ofNullable(securityContext.getAuthentication())
        <%_ } else { _%>
        return ReactiveSecurityContextHolder.getContext()
            .map(SecurityContext::getAuthentication)
        <%_ } _%>
            .filter(authentication -> authentication.getCredentials() instanceof String)
            .map(authentication -> (String) authentication.getCredentials());
    }
<%_ } _%>

    /**
     * Check if a user is authenticated.
     *
     * @return true if the user is authenticated, false otherwise.
     */
    public static <% if (!reactive) { %>boolean<% } else { %>Mono<Boolean><% } %> isAuthenticated() {
<%_ if (!reactive) { _%>
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication != null &&
            getAuthorities(authentication).noneMatch(AuthoritiesConstants.ANONYMOUS::equals);
<%_ } else { _%>
        return ReactiveSecurityContextHolder.getContext()
            .map(SecurityContext::getAuthentication)
            .map(Authentication::getAuthorities)
            .map(authorities -> authorities.stream()
                .map(GrantedAuthority::getAuthority)
                .noneMatch(AuthoritiesConstants.ANONYMOUS::equals)
            );
<%_ } _%>
    }

    /**
     * If the current user has a specific authority (security role).
     * <p>
     * The name of this method comes from the {@code isUserInRole()} method in the Servlet API.
     *
     * @param authority the authority to check.
     * @return true if the current user has the authority, false otherwise.
     */
    public static <% if (!reactive) { %>boolean<% } else { %>Mono<Boolean><% } %> isCurrentUserInRole(String authority) {
<%_ if (!reactive) { _%>
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication != null &&
            getAuthorities(authentication).anyMatch(authority::equals);
<%_ } else { _%>
        return ReactiveSecurityContextHolder.getContext()
            .map(SecurityContext::getAuthentication)
            .map(Authentication::getAuthorities)
            .map(authorities -> authorities.stream()
                .map(GrantedAuthority::getAuthority)
                .anyMatch(authority::equals)
            );
<%_ } _%>
    }

<%_ if (!reactive) { _%>
    private static Stream<String> getAuthorities(Authentication authentication) {
        <%_ if (authenticationType === 'oauth2') { _%>
        Collection<? extends GrantedAuthority> authorities = authentication instanceof JwtAuthenticationToken ?
            extractAuthorityFromClaims(((JwtAuthenticationToken) authentication).getToken().getClaims())
            : authentication.getAuthorities();
        return authorities.stream()
        <%_ } else { _%>
        return authentication.getAuthorities().stream()
        <%_ } _%>
            .map(GrantedAuthority::getAuthority);
    }

<%_ } _%>
<%_ if (authenticationType === 'oauth2') { _%>
    public static List<GrantedAuthority> extractAuthorityFromClaims(Map<String, Object> claims) {
        return mapRolesToGrantedAuthorities(getRolesFromClaims(claims));
    }

    @SuppressWarnings("unchecked")
    private static Collection<String> getRolesFromClaims(Map<String, Object> claims) {
        return (Collection<String>) claims.getOrDefault("groups",
            claims.getOrDefault("roles", new ArrayList<>()));
    }

    private static List<GrantedAuthority> mapRolesToGrantedAuthorities(Collection<String> roles) {
        return roles.stream()
            .filter(role -> role.startsWith("ROLE_"))
            .map(SimpleGrantedAuthority::new)
            .collect(Collectors.toList());
    }
<%_ } _%>
}
